from flask import Blueprint, jsonify, request
import json
from db import db1

bp_admin = Blueprint('admin', __name__)


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_admin.route('/roles', methods=['POST', 'GET'])
def roles():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from roles where name = "%s" ''' % (data['name'])
        res1 = db1.findall(sql1)
        if res1:
            return jsonify({'code': 20010, 'mes': '该角色已存在'})
        else:
            sql = '''insert into roles values(0,"%s")''' % (data['name'])
            db1.update(sql)
            return jsonify({'code': 200})
    elif request.method == 'GET':
        sql1 = '''select * from roles'''
        res1 = db1.findall(sql1)
        sql2 = '''select * from resources'''
        res2 = db1.findall(sql2)
        return jsonify({'code': 200, 'list1': res1, 'list2': res2})


@bp_admin.route('/resources', methods=['POST'])
def resources():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from resources where name = "%s" ''' % (data['name'])
        res1 = db1.findall(sql1)
        if res1:
            return jsonify({'code': 20010, 'mes': '该资源已存在'})
        else:
            sql = '''insert into resources values(0,"%s","%s")''' % (data['name'], data['url'])
            db1.update(sql)
            return jsonify({'code': 200})


@bp_admin.route('/jszy', methods=['POST', 'GET'])
def jszy():
    if request.method == 'POST':
        data = get_data()
        sql = '''delete from role_resources where role_id = %d ''' % (int(data['role_id']))
        db1.update(sql)
        ids = data['ids']
        for i in ids:
            sql = '''insert into role_resources values(0,%d,%d,%d)''' % (int(data['role_id']), i, 1)
            db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        id = request.args.get('id')

        sql = '''select resources_id from role_resources where role_id = %d ''' % (int(id))
        res = db1.findall(sql)
        list1 = []
        for i in res:
            list1.append(i['resources_id'])
        print(list1)
        return jsonify({'code': 200, 'idlist': list1})


@bp_admin.route('/user', methods=['POST'])
def user():
    if request.method == 'POST':
        data = get_data()
        sql = '''select id from admin_user where name = "%s" ''' % (data['name'])
        res = db1.findall(sql)
        if res:
            return jsonify({'code': 20010, 'mes': '手机号已存在'})
        else:
            sql = '''insert into admin_user values(0,"%s","%s",%d,%d)''' % (
            data['name'], "123", 1, int(data['role_id']))
            db1.update(sql)
            return jsonify({'code': 200})
